import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import NProgress from 'nprogress'

// 基础路由（无需认证）
const basicRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: '登录',
      hideInMenu: true,
      requiresAuth: false
    }
  },
  {
    path: '/',
    redirect: '/dashboard/workplace'
  }
]

// 主要路由（需要认证）
const mainRoutes: RouteRecordRaw[] = [
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/layout/index.vue'),
    meta: {
      title: '仪表盘',
      icon: 'icon-dashboard',
      requiresAuth: true
    },
    children: [
      {
        path: 'workplace',
        name: 'Workplace',
        component: () => import('@/views/dashboard/workplace/index.vue'),
        meta: {
          title: '工作台',
          icon: 'icon-desktop',
          requiresAuth: true
        }
      },
      {
        path: 'analysis',
        name: 'Analysis',
        component: () => import('@/views/dashboard/analysis/index.vue'),
        meta: {
          title: '分析页',
          icon: 'icon-bar-chart',
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/system',
    name: 'System',
    component: () => import('@/layout/index.vue'),
    meta: {
      title: '系统管理',
      icon: 'icon-settings',
      requiresAuth: true
    },
    children: [
      {
        path: 'user',
        name: 'SystemUser',
        component: () => import('@/views/system/user/index.vue'),
        meta: {
          title: '用户管理',
          icon: 'icon-user',
          requiresAuth: true,
          permission: 'system:user:list'
        }
      },
      {
        path: 'role',
        name: 'SystemRole',
        component: () => import('@/views/system/role/index.vue'),
        meta: {
          title: '角色管理',
          icon: 'icon-safe',
          requiresAuth: true,
          permission: 'system:role:list'
        }
      },
      {
        path: 'menu',
        name: 'SystemMenu',
        component: () => import('@/views/system/menu/index.vue'),
        meta: {
          title: '菜单管理',
          icon: 'icon-menu',
          requiresAuth: true,
          permission: 'system:menu:list'
        }
      },
      {
        path: 'dept',
        name: 'SystemDept',
        component: () => import('@/views/system/dept/index.vue'),
        meta: {
          title: '部门管理',
          icon: 'icon-branch',
          requiresAuth: true,
          permission: 'system:dept:list'
        }
      }
    ]
  },
  {
    path: '/message',
    name: 'Message',
    component: () => import('@/layout/index.vue'),
    meta: {
      title: '消息中心',
      icon: 'icon-message',
      requiresAuth: true
    },
    children: [
      {
        path: '',
        name: 'MessageIndex',
        component: () => import('@/views/message/index.vue'),
        meta: {
          title: '消息中心',
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/layout/index.vue'),
    meta: {
      title: '个人中心',
      hideInMenu: true,
      requiresAuth: true
    },
    children: [
      {
        path: '',
        name: 'ProfileIndex',
        component: () => import('@/views/profile/index.vue'),
        meta: {
          title: '个人中心',
          requiresAuth: true
        }
      }
    ]
  }
]

// 404路由
const notFoundRoute: RouteRecordRaw = {
  path: '/:pathMatch(.*)*',
  name: 'NotFound',
  component: () => import('@/views/error/404.vue'),
  meta: {
    title: '页面不存在',
    hideInMenu: true,
    requiresAuth: false
  }
}

const routes = [...basicRoutes, ...mainRoutes, notFoundRoute]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    }
    return { top: 0 }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  
  const userStore = useUserStore()
  const token = userStore.token

  // 设置页面标题
  if (to.meta?.title) {
    document.title = `${to.meta.title} - MMC管理系统`
  }

  // 如果是登录页面，且已登录，则跳转到首页
  if (to.path === '/login' && token) {
    next('/')
    return
  }

  // 如果需要认证但未登录，跳转到登录页
  if (to.meta?.requiresAuth && !token) {
    next('/login')
    return
  }

  // 如果已登录但用户信息为空，则获取用户信息
  if (token && !userStore.userInfo?.id) {
    try {
      await userStore.getUserInfo()
    } catch (error) {
      // 获取用户信息失败，可能token已过期
      await userStore.logout()
      next('/login')
      return
    }
  }

  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router 